<template>
  <section>
    <el-card v-if="records.length <= 0"
             style="text-align: right; margin-bottom: 20px">
      <el-button style="margin-right: 20px"
                 :disabled="downloadDisabled"
                 :title="downloadTootip"
                 @click="download(templateDownloadUrl)">
        下载模板
      </el-button>
      <upload :api="api"
              @upload="upload" />
      <el-button style="margin-left: 20px"
                 @click="back"> 返 回</el-button>
    </el-card>
    <table-box-import :api="api"
                      :columns="columns"
                      :records="records"
                      :total="total" />
  </section>
</template>
<script>
import TableBoxImport from "./TableBoxImport.vue";
import upload from "./UploadExcel.vue";
import { admin } from "@/api"

export default {
  name: "BasicImport",
  components: { TableBoxImport, upload },
  props: {
    templateUrl: {
      type: String
    },
    templateName: {
      type: String
    },
    columns: {
      type: Array
    },
    api: {
      type: Object
    },
    remarks: {
      type: Array
    }
  },
  data () {
    return {
      records: [],
      total: 0,
      statusArr: ["success", "pass", "fail"],
      visible: false,
      isNext: true,
      cancel: false,
      // 为导入的数据被处理之后形成的数据，
      pageList: [],
      list: [],
      successCount: 0,
      paging: {
        size: 10,
        page: 1
      },
      showMsg: false,
      active: 1,
      listTotal: 0, //提交总数
      loading: false,
      isSaveDisabled: true, // 导入后保存是否可点击
      passCount: 0, // 导入通过的条数,
      excelTemplates: [],
    };
  },
  computed: {
    successPercentage () {
      return (
        Math.round((this.successCount / this.list.length) * 100 * 100) / 100
      );
    },
    templateDownloadUrl () {
      const remoteUrl = this.excelTemplates
        ?.filter(item => item.name === this.templateName)
        ?.[0]?.url;

      return remoteUrl || this.templateUrl;
    },
    downloadDisabled () {
      return this.excelTemplates?.length === 0;
    },
    downloadTootip () {
      return this.downloadDisabled ? '加载模板中...' : null
    }
  },
  mounted () {
    this.loadTemplates();
  },
  methods: {
    async loadTemplates () {
      const response = await admin.loadExcelTemplates();
      this.excelTemplates = response.data;
    },
    download (url) {
      let newUrl = url.includes('https') ? url : url.replace('http', 'https')
      window.location.href = newUrl;
    },
    upload (data) {
      this.records = data;
      this.total = data.length;
    },
    back () {
      this.records = [];
      this.$router.back();
    },
    // 批量提交， 允许存在错误项的时候提交数据，将会只提交成功项
    handleSubmit () {
      this.loading = true;
      // this.api.batchInsert(data).then((res) => {
      //   if (res.code === 0) {
      //     this.records = [];
      //   }
      //   // console.log("res", res)
      // })
    }
  }
};
</script>
